<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>基本属性</h3>
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="团购折扣" prop="discount">
          <el-input v-model="dataForm.discount" />
        </el-form-item>
        <el-form-item label="团购人数要求" prop="discountMember">
          <el-input v-model="dataForm.discountMember" />
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
            v-model="dataForm.expireTime"
            type="datetime"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card">
      <h3>选择商品</h3>
      <div class="filter-container">
        <el-input
          v-model="listQuery.name"
          clearable
          class="filter-item"
          style="width: 160px;"
          placeholder="请输入商品名称"
        />
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      </div>

      <!-- 查询结果 -->
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" class="table-expand">
              <el-form-item label="商品编号">
                <span>{{ props.row.goodsSn }}</span>
              </el-form-item>
              <el-form-item label="宣传画廊">
                <img v-for="pic in props.row.gallery" :key="pic" :src="pic" class="gallery">
              </el-form-item>
              <el-form-item label="商品介绍">
                <span>{{ props.row.brief }}</span>
              </el-form-item>
              <el-form-item label="商品单位">
                <span>{{ props.row.unit }}</span>
              </el-form-item>
              <el-form-item label="关键字">
                <span>{{ props.row.keywords }}</span>
              </el-form-item>
              <el-form-item label="类目ID">
                <span>{{ props.row.categoryId }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>

        <el-table-column align="center" label="商品编号" prop="goodsSn" />

        <el-table-column align="center" min-width="100" label="名称" prop="name">
          <!-- <template slot-scope="scope">
            <el-input v-model="dataForm.goodsName" :value="scope.row.name"></el-input>
          </template>-->
        </el-table-column>

        <el-table-column align="center" property="iconUrl" label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.picUrl" width="40">
          </template>
        </el-table-column>

        <el-table-column align="center" label="市场售价" prop="counterPrice" />

        <el-table-column align="center" label="当前价格" prop="retailPrice" />

        <el-table-column align="center" label="是否新品" prop="isNew">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.isNew ? 'success' : 'error' "
            >{{ scope.row.isNew ? '新品' : '非新品' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="是否热品" prop="isHot">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.isHot ? 'success' : 'error' "
            >{{ scope.row.isHot ? '热品' : '非热品' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="是否在售" prop="isOnSale">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.isOnSale ? 'success' : 'error' "
            >{{ scope.row.isOnSale ? '在售' : '未售' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-radio
              v-model="listQuery.goodsId"
              :label="scope.row.id"
              border
              size="medium"
              @change="bindGoods(scope.row.name)"
            >绑定</el-radio>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.current"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </el-card>

    <el-card class="box-card">
      <h3>商品库存</h3>
      <el-table :data="products">
        <el-table-column property="value" label="货品规格">
          <template slot-scope="scope">
            <el-tag v-for="tag in scope.row.specifications" :key="tag">{{ tag }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column property="price" label="货品售价" />
        <el-table-column property="number" label="货品数量" />
        <el-table-column property="url" label="货品图片">
          <template slot-scope="scope">
            <img v-if="scope.row.url" :src="scope.row.url" width="40">
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-radio
              v-model="dataForm.productId"
              :label="scope.row.id"
              border
              size="medium"
              @change="changeRadio(scope.row)"
            >绑定</el-radio>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handlePublish">创建</el-button>
    </div>
  </div>
</template>
<style>
.el-card {
  margin-bottom: 10px;
}

.op-container {
  display: flex;
  justify-content: center;
}
</style>
<script>
import { listGoods, deleteGoods, goodsStandard } from '@/api/goods';
import {
  createRules,
  editRules,
  listAllRulesByPage,
  deleteRules
} from '@/api/groupon';
import Pagination from '@/components/Pagination';
export default {
  name: 'RuleCreate',
  components: { Pagination },
  data() {
    return {
      list: [],
      total: 0,
      detailDialogVisible: false,
      detailStandardVisible: false,
      goodsDetail: {},
      products: [
        {
          id: 0,
          specifications: ['标准'],
          price: 10.0,
          number: 10,
          url:
            'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80'
        }
      ],
      specifications: [
        {
          specification: '规格1',
          value: '007',
          picUrl:
            'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80'
        }
      ],
      listQuery: {
        current: 1,
        size: 5,
        goodsId: undefined,
        goodsSn: undefined,
        name: undefined,
        orderBy: 'add_time',
        sort: 'desc'
      },
      dataForm: {
        id: undefined,
        goodsId: '',
        goodsName: '',
        discount: '',
        discountMember: '',
        expireTime: undefined,
        product: undefined,
        productId: undefined,
        specifications: undefined,
        productNumber: undefined
      },
      rules: {
        goodsId: [{ required: true, message: '商品不能为空', trigger: 'blur' }],
        goodsName: [
          { required: true, message: '商品不能为空', trigger: 'blur' }
        ],
        discount: [
          { required: true, message: '团购折扣不能为空', trigger: 'blur' }
        ],
        discountMember: [
          { required: true, message: '团购人数不能为空', trigger: 'blur' }
        ],
        expireTime: [
          { required: true, message: '过期时间不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  watch: {
    'listQuery.goodsId'() {
      goodsStandard({ id: this.listQuery.goodsId }).then(response => {
        const data = response.data.data;
        this.specifications = data.specifications;
        this.products = data.productForm;
      });
    }
  },
  created() {
    const id = this.$route.query.id;
    if (id) {
      listAllRulesByPage({ id }).then(response => {
        const list = response.data.data.list;
        const product = list[0];
        this.listQuery.goodsId = product.goodsId;
        this.dataForm = product;
      });
    }
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      listGoods(this.listQuery)
        .then(response => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .then(res => {
          const id = this.$router.id;
          id && (this.listQuery.goodsId = id);
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    bindGoods(name) {
      this.dataForm.goodsName = name;
    },
    changeRadio(product) {
      this.dataForm.productId = product.id;
      this.dataForm.productPrice = product.price;
      this.dataForm.goodsId = product.goodsId;
      this.dataForm.specifications = JSON.stringify(product.specifications);
      this.dataForm.productNumber = product.stock;
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    showDetail(detail) {
      this.goodsDetail = detail;
      this.detailDialogVisible = true;
    },
    showStandard(id) {
      goodsStandard({ id }).then(response => {
        const data = response.data.data;
        this.specifications = data.specifications;
        this.productForm = data.productForm;
      });
      this.detailStandardVisible = true;
    },
    handleCancel() {},
    handlePublish() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.$route.query.id) {
            editRules(this.dataForm)
              .then(response => {
                this.$router.push({ path: '/promotion/groupon-rule' });
                this.$notify.success({
                  title: '成功',
                  message: '创建团购规则成功'
                });
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                });
              });
          } else {
            createRules(this.dataForm)
              .then(response => {
                this.$router.push({ path: '/promotion/groupon-rule' });
                this.$notify.success({
                  title: '成功',
                  message: '创建团购规则成功'
                });
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                });
              });
          }
        }
      });
    }
  }
};
</script>
